var book = {
    title: "Professional JavaScript",
    authors: ["Nicholas C. Zakas", "Bobby"],
    edition: 3,
    year: 2011
};

//把一个JavaScript 对象序列化为一个JSON 字符串
function toJsonStrTest() {
    var jsonText = JSON.stringify(book);
    console.log(jsonText);
}

//得到相应的JavaScript 值
function toJsObjTest() {
    var jsonText = JSON.stringify(book);
    var bookCopy = JSON.parse(jsonText);
    console.log(bookCopy);
}

//过滤结果
function toJsonStrFilterTest() {
    var jsonText = JSON.stringify(book, ["title", "edition"]);
    console.log(jsonText);
}

function toJsonStrFilterTest2() {
    var jsonText = JSON.stringify(book, function (key, value) {
        switch (key) {
            case "authors":
                return value.join(",");
            case "year":
                return 5000;
            case "edition":
                //如果函数返回了undefined，那么相应的属性会被忽略。
                return undefined;
            default:
                return value;
        }
    });
    console.log(jsonText);
}

//字符串缩进
function toJsonStrFilterTest3() {
    var jsonText = JSON.stringify(book, null, 4);
    console.log(jsonText);
    var jsonText2 = JSON.stringify(book, null, "--");
    console.log(jsonText2);
}

function toJsonTest() {
    var book = {
        "title": "Professional JavaScript",
        "authors": [
            "Nicholas C. Zakas"
        ],
        edition: 3,
        year: 2011,
        toJSON: function () {
            return this.title;
        }
    };
    var jsonText = JSON.stringify(book);
    console.log(jsonText);
}

function parseTest() {
    var book = {
        "title": "Professional JavaScript",
        "authors": [
            "Nicholas C. Zakas"
        ],
        edition: 3,
        year: 2010,
        releaseDate: new Date(2011, 11, 1)
    };
    var jsonText = JSON.stringify(book);
    var bookCopy = JSON.parse(jsonText, function (key, value) {
        if (key == "releaseDate") {
            return new Date(value);
        } else {
            return value;
        }
    });
    console.log(bookCopy.releaseDate.getFullYear());
}